package com.woniuxy.sales.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.sales.common.RedisConst;
import com.woniuxy.sales.model.dto.AddressRequest;
import com.woniuxy.sales.model.entity.Address;
import com.woniuxy.sales.model.entity.China;
import com.woniuxy.sales.service.AddressService;
import com.woniuxy.sales.mapper.AddressMapper;
import com.woniuxy.sales.service.ChinaService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
* @author Administrator
* @description 针对表【address】的数据库操作Service实现
* @createDate 2024-11-01 10:29:07
*/
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService{
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ChinaService chinaService;
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 查询所有的省份
     */
    @Override
    public List<China> getAllProvince() {
        List<China> list;
        // 判断缓存中是否有key
        if (!redisTemplate.hasKey(RedisConst.PROVINCES)) {
            // 查询数据库
            list = chinaService.list(
                    Wrappers.lambdaQuery(China.class).eq(China::getLevel, 1).orderByAsc(China::getId)
            );
            // 查询结果放入Redis缓存，通过zset集合存储，id是分数
            list.forEach(china -> redisTemplate.opsForZSet().add(RedisConst.PROVINCES, china, china.getId()));
        } else {
            // 从Redis中获取所有元素
            Set<China> members = redisTemplate.opsForZSet().range(RedisConst.PROVINCES, 0, -1);
            list = new ArrayList<>(members);
        }
        return list;
    }
    /**
     * 通过省的id查询省下所有的城市
     * #root.methodName 动态获取方法名称
     * #provinceId 动态获取方法参数
     */
    @Cacheable(cacheNames = RedisConst.CITIES, key = "#root.methodName + #provinceId")
    @Override
    public List<China> getAllCities(Integer provinceId) {
        List<China> list = chinaService.list(Wrappers.lambdaQuery(China.class)
                .eq(Objects.nonNull(provinceId), China::getPid, provinceId));
        return list;
    }
    /**
     * 通过城市的id查询城市下所有的地区
     */
    @Override
    @Cacheable(cacheNames = RedisConst.DISTRICTS, key = "#root.methodName + #cityId")
    public List<China> getAllDistricts(Integer cityId) {
        List<China> list = chinaService.list(Wrappers.lambdaQuery(China.class)
                .eq(Objects.nonNull(cityId), China::getPid, cityId));
        return list;
    }
    @Override
    @Transactional  //开启事务
    public void addAddress(AddressRequest addressRequest, Integer userId) {
        // 根据省份id，获取省份名称
        China province = chinaService.findById(addressRequest.getProvince());
        // 获取城市id，获取城市名称
        China city = chinaService.findById(addressRequest.getCity());
        // 获取区/县id，获取区/县名称
        Integer district = addressRequest.getDistrict();
        // Optional.ofNullable(district) 创建一个 Optional 对象，然后调用 map(chinaService::findById) 方法来处理 district 不为空的情况，最后使用 orElse(null) 来处理 district 为空的情况，避免了显式的 if 判断语句，使代码更加简洁和优雅。
        China area = Optional.ofNullable(district)
                .map(chinaService::findById)
                .orElse(null);
        // 封装地址信息
        Address address = new Address();
        // 属性拷贝
        BeanUtils.copyProperties(addressRequest, address);
        // 属性不同的则单独设置
        address.setProvince(province.getId());
        address.setCity(city.getId());
        //如果为空，则赋值空字符串
        address.setArea(area == null ? null : area.getId());
        address.setStatus("1");
        address.setTelephone(addressRequest.getTelephone());
        address.setUserId(userId);
        address.setAllAddress(province.getName()+city.getName()+area.getName()+addressRequest.getDetailAddress());

        // 判断是否为默认地址
        if (address.getIsDefault() == 1) {
            // 修改其他地址为不是默认地址，将isDefault = 0
            this.update(Wrappers.lambdaUpdate(Address.class)
                    .set(Address::getIsDefault, "0").eq(Address::getUserId, userId));
        }
        // 添加地址
        addressMapper.insert(address);
    }

    @Override
    public List<Address> query(Integer userId) {
        LambdaUpdateWrapper<Address> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(Address::getUserId, userId).orderByDesc(Address::getIsDefault);
        List<Address> addresses = addressMapper.selectList(wrapper);
        return addresses;
    }
//    @Override
//    public List<AddressVo> query(Integer userId) {
//        LambdaUpdateWrapper<Address> wrapper = Wrappers.lambdaUpdate();
//        wrapper.eq(Address::getUserId, userId);
//        List<Address> addresses = addressMapper.selectList(wrapper);
//        List<AddressVo> addressVos = addresses.stream().map(addr -> {
//            AddressVo addressVo = BeanUtil.copyProperties(addr, AddressVo.class);
//            addressVo.setAllAddress(addr.getProvince() + addr.getCity() + addr.getArea() + addr.getDetailAddress());
//            return addressVo;
//        }).collect(Collectors.toList());
//        return addressVos;
//    }

    @Override
    public void remove(Integer id) {
        addressMapper.deleteById(id);
    }

    @Override
    public void edit(Address address) {
        // 根据省份id，获取省份名称
        China province = chinaService.findById(address.getProvince());
        // 获取城市id，获取城市名称
        China city = chinaService.findById(address.getCity());
        // 获取区/县id，获取区/县名称
        Integer district = address.getArea();
        // Optional.ofNullable(district) 创建一个 Optional 对象，然后调用 map(chinaService::findById) 方法来处理 district 不为空的情况，最后使用 orElse(null) 来处理 district 为空的情况，避免了显式的 if 判断语句，使代码更加简洁和优雅。
        China area = Optional.ofNullable(district)
                .map(chinaService::findById)
                .orElse(null);

        address.setAllAddress(province.getName()+city.getName()+area.getName()+address.getDetailAddress());
        // 判断是否为默认地址
        if (address.getIsDefault() == 1) {
            // 修改其他地址为不是默认地址，将isDefault = 0
            this.update(Wrappers.lambdaUpdate(Address.class)
                    .set(Address::getIsDefault, "0").eq(Address::getUserId, address.getUserId()));
        }
        addressMapper.updateById(address);
    }
//    @Override
//    public void edit(AddressRequest addressRequest) {
//        Address address = BeanUtil.copyProperties(addressRequest, Address.class);
//        addressMapper.updateById(address);
//    }



}




